<?php

require_once 'vendor/autoload.php';

use Smalot\Cups\Builder\Builder;
use Smalot\Cups\Manager\PrinterManager;
use Smalot\Cups\Transport\Client;
use Smalot\Cups\Transport\ResponseParser;
use Http\Client\Socket\Client as HttpClient;

/**
 * 快速打印机连接测试
 * 用于验证CUPS服务器连接和打印机状态
 */

function testCupsConnection($cupsUrl = 'http://localhost:631') {
    echo "测试CUPS服务器连接: $cupsUrl\n";
    
    try {
        $context = stream_context_create([
            'http' => [
                'timeout' => 5,
                'method' => 'GET'
            ]
        ]);
        
        $response = @file_get_contents($cupsUrl, false, $context);
        
        if ($response !== false) {
            echo "✓ CUPS服务器连接成功\n";
            return true;
        } else {
            echo "❌ 无法连接到CUPS服务器\n";
            return false;
        }
    } catch (Exception $e) {
        echo "❌ 连接错误: " . $e->getMessage() . "\n";
        return false;
    }
}

function listAvailablePrinters() {
    echo "\n获取系统打印机列表...\n";
    
    // Windows系统
    if (PHP_OS_FAMILY === 'Windows') {
        $output = [];
        exec('wmic printer get name,status,portname 2>nul', $output);
        
        if (!empty($output)) {
            echo "Windows系统打印机:\n";
            foreach ($output as $line) {
                if (trim($line) && !strpos($line, 'Name')) {
                    echo "  - " . trim($line) . "\n";
                }
            }
        }
    }
    
    // Linux/macOS系统
    else {
        $output = [];
        exec('lpstat -p 2>/dev/null', $output);
        
        if (!empty($output)) {
            echo "CUPS系统打印机:\n";
            foreach ($output as $line) {
                echo "  - " . trim($line) . "\n";
            }
        } else {
            echo "未找到CUPS打印机，请检查CUPS服务状态\n";
        }
    }
}

function createTestPrintJob() {
    echo "\n创建测试打印任务...\n";
    
    try {
        $builder = new Builder();
        $client = new Client();
        $httpClient = new HttpClient();
        $responseParser = new ResponseParser();
        
        $printerManager = new PrinterManager($builder, $httpClient, $responseParser);
        
        echo "✓ CUPS-IPP客户端初始化成功\n";
        
        // 创建简单的测试文件
        $testFile = 'test_print.txt';
        $testContent = "CUPS-IPP PHP库测试\n" .
                      "时间: " . date('Y-m-d H:i:s') . "\n" .
                      "这是一个测试打印文档";
        
        file_put_contents($testFile, $testContent);
        echo "✓ 测试文件创建: $testFile\n";
        
        return $testFile;
        
    } catch (Exception $e) {
        echo "❌ 创建测试任务失败: " . $e->getMessage() . "\n";
        return false;
    }
}

function printInstructions() {
    echo "\n" . str_repeat('=', 50) . "\n";
    echo "📋 本地打印测试指南\n";
    echo str_repeat('=', 50) . "\n\n";
    
    echo "🔧 环境准备:\n";
    echo "1. 安装CUPS服务 (Linux/macOS) 或确保Windows打印服务运行\n";
    echo "2. 配置至少一台打印机\n";
    echo "3. 运行 'composer install' 安装依赖\n\n";
    
    echo "🖨️  打印机配置:\n";
    echo "- 访问 http://localhost:631 (CUPS Web界面)\n";
    echo "- 添加打印机: Administration > Add Printer\n";
    echo "- 记录打印机URI (例如: ipp://localhost:631/printers/HP_LaserJet)\n\n";
    
    echo "🧪 测试步骤:\n";
    echo "1. 运行此脚本检查连接: php quick_print_test.php\n";
    echo "2. 修改 example_print_test.php 中的打印机URI\n";
    echo "3. 运行完整测试: php example_print_test.php\n\n";
    
    echo "🔍 故障排除:\n";
    echo "- 检查CUPS服务状态: systemctl status cups\n";
    echo "- 检查打印机状态: lpstat -p\n";
    echo "- 检查打印队列: lpq\n";
    echo "- 测试打印: echo 'test' | lp -d printer_name\n\n";
}

// 执行测试
echo "=== CUPS-IPP 快速连接测试 ===\n\n";

// 1. 测试CUPS连接
$cupsConnected = testCupsConnection();

// 2. 列出可用打印机
listAvailablePrinters();

// 3. 创建测试任务
$testFile = createTestPrintJob();

// 4. 显示使用说明
printInstructions();

echo "测试完成！\n";

if ($testFile && file_exists($testFile)) {
    echo "\n清理测试文件: $testFile\n";
    unlink($testFile);
}